package com.cby.android.base.contentprovider

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import java.lang.IllegalArgumentException
import android.content.ContentUris
import android.database.SQLException
import android.os.Bundle
import android.util.Log


/**
 * @description: MyContentProvider
 *
 * @author ChenBaoyang
 * @date 2021/10/13 15:42
 */
class MyContentProvider : ContentProvider() {

    var mDbHelper: DBHelper? = null
    var db: SQLiteDatabase? = null

    private val mMatcher:UriMatcher by lazy {
        UriMatcher(UriMatcher.NO_MATCH).apply {
            this.addURI(Constant.AUTHORITY,Constant.TABLE_NAME, Constant.ITEM)
            this.addURI(Constant.AUTHORITY, Constant.TABLE_NAME+"/#", Constant.ITEM_ID)
        }
    }

    override fun onCreate(): Boolean {
        context?.let {
            InitializeManager.instance.init(it)
            mDbHelper = DBHelper(it)
            db = mDbHelper!!.readableDatabase
            db?.apply {
                this.execSQL("delete from user")
                this.execSQL("insert into user(name, age) values('Carson', 20)")
                this.execSQL("insert into user(name, age) values('Kobe', 28)")
            }

        }
        return true
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        var c: Cursor? = when (mMatcher.match(uri)) {
            Constant.ITEM -> db!!.query(
                Constant.TABLE_NAME,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                sortOrder
            )
            Constant.ITEM_ID -> db!!.query(
                Constant.TABLE_NAME,
                projection,
                Constant.COLUMN_ID + "=" + uri.lastPathSegment,
                selectionArgs,
                null,
                null,
                sortOrder
            )
            else -> throw IllegalArgumentException("Unknown URI$uri")
        }

        c?.setNotificationUri(context!!.contentResolver, uri)
        return c
    }

    override fun getType(uri: Uri): String? {
        // 根据匹配规则返回对应的类型
        return when (mMatcher.match(uri)) {
            Constant.ITEM -> Constant.CONTENT_TYPE
            Constant.ITEM_ID -> Constant.CONTENT_ITEM_TYPE
            else -> throw IllegalArgumentException("Unknown URI$uri")
        }
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        require(mMatcher.match(uri) == Constant.ITEM) { "Unknown URI$uri" }
        val rowId: Long = db!!.insert(Constant.TABLE_NAME, null, values)
        if (rowId > 0) {
            val noteUri = ContentUris.withAppendedId(Constant.CONTENT_URI, rowId)
            context!!.contentResolver.notifyChange(noteUri, null)
            return noteUri
        }

        throw SQLException("Failed to insert row into $uri")
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        db?.delete(Constant.TABLE_NAME,selection,selectionArgs)
        return 0
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        require(mMatcher.match(uri) == Constant.ITEM) { "Unknown URI$uri" }
        val rows: Int = db!!.update(Constant.TABLE_NAME,  values,null, null)
        if (rows > 0) {
            context!!.contentResolver.notifyChange(Constant.CONTENT_URI, null)
            return rows
        }

        throw SQLException("Failed to insert row into $uri")
    }


    override fun call(method: String, arg: String?, extras: Bundle?
    ): Bundle? {
        Log.i("chenby_content",
            String.format("method=%s,arg=%s", method, arg)
        )
        return ContentProviderHandler.instance.doCall(method, arg, extras)
    }
}